package bb.lanxing.activity.team;

import android.content.Intent;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.POISearchResultAdapter;
import bb.lanxing.manager.SystemLocationManagerNew;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.RxPermissionUtil;

public class TeamCreateLocationActivity extends BaseActivity {
    private TextureMapView textureMapView;
    private BaiduMap mBaiduMap;
    private ListView resultList;
    private POISearchResultAdapter pOISearchResultAdapter;
    private RelativeLayout locationLayout;
    private TextView locationText;
    private TextView addressText;
    private TextView commitBtn;

    private SuggestionSearch mSuggestionSearch = SuggestionSearch.newInstance();

    private GeoCoder mGeoCoder = GeoCoder.newInstance();

    private String currentCity = "北京市";
    private LatLng currentLocation;
    private String currentAddress;

    private boolean isFirstRun = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_create_location);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());

        textureMapView = findViewById(R.id.textureMapView);
        textureMapView.removeViewAt(1);
        textureMapView.showScaleControl(false);
        textureMapView.showZoomControls(false);
        mBaiduMap = textureMapView.getMap();
        mBaiduMap.setOnMapLoadedCallback(() -> {
            if (getIntent().getDoubleExtra("lat", 0) == 0) {
                requestLocationPermission();
                searchAddress();
            } else {
                LatLng mStartLatlng = new LatLng(getIntent().getDoubleExtra("lat", 0.0),
                        getIntent().getDoubleExtra("lng", 0));
                LatLng startAddrLatLng = BiCiCoorConverter.earth2Baidu(mStartLatlng);
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLngZoom(startAddrLatLng, 18.0f));
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
                if (isFirstRun) {
                    searchAddress();
                    isFirstRun = false;
                }
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                searchAddress();
            }
        });
        mGeoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                currentAddress = reverseGeoCodeResult.getSematicDescription();
                locationText.setText(currentAddress);
                addressText.setText(reverseGeoCodeResult.getAddress());
                if (reverseGeoCodeResult.getAddressDetail() != null) {
                    currentCity = reverseGeoCodeResult.getAddressDetail().city;
                }
            }
        });

        EditText address_et = findViewById(R.id.address_et);
        address_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    return;
                }
                mSuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(s.toString()).city(currentCity));
            }
        });
        mSuggestionSearch.setOnGetSuggestionResultListener(suggestionResult -> {
            if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
                return;
            }
            List<PoiInfo> list = new ArrayList<>();
            for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
                PoiInfo item = new PoiInfo();
                item.setName(info.getKey());
                item.setCity(info.getAddress());
                item.setLocation(info.getPt());
                list.add(item);
            }
            pOISearchResultAdapter.updateData(list);
            resultList.setVisibility(View.VISIBLE);
            locationLayout.setVisibility(View.GONE);
            commitBtn.setVisibility(View.GONE);
        });

        resultList = findViewById(R.id.resultList);
        pOISearchResultAdapter = new POISearchResultAdapter(this);
        resultList.setAdapter(pOISearchResultAdapter);
        resultList.setOnItemClickListener((parent, view, position, id) -> {
            resultList.setVisibility(View.GONE);
            locationLayout.setVisibility(View.VISIBLE);
            commitBtn.setVisibility(View.VISIBLE);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                    .newLatLng(((PoiInfo) pOISearchResultAdapter.getItem(position)).location));
        });

        locationLayout = findViewById(R.id.locationLayout);
        locationText = findViewById(R.id.locationText);
        addressText = findViewById(R.id.addressText);

        commitBtn = findViewById(R.id.commitBtn);
        commitBtn.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("StartAddr", currentAddress);
            intent.putExtra("lat", currentLocation.latitude);
            intent.putExtra("lng", currentLocation.longitude);
            intent.putExtra("CityId", currentCity);
            setResult(-1, intent);
            finish();
        });
    }

    private SystemLocationManagerNew.GpsChangedListener mGpsChangedListener = new SystemLocationManagerNew.GpsChangedListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            LatLng mStartLatlng = new LatLng(location.getLatitude(), location.getLongitude());
            LatLng startAddrLatLng = BiCiCoorConverter.earth2Baidu(mStartLatlng);
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLngZoom(startAddrLatLng, 17.0f));
            SystemLocationManagerNew.getInstance().unregisterGpsChangedListener(mGpsChangedListener);
        }
    };

    private void searchAddress() {
        currentLocation = mBaiduMap.getProjection().fromScreenLocation(
                new Point(textureMapView.getWidth() / 2, textureMapView.getHeight() / 2));
        mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(currentLocation));
    }

    public void requestLocationPermission() {
        RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getLocationOnlyPermission())
                .permissionRequestEachCombined(this, new RxPermissionUtil.PermissionCallBack() {
                    @Override
                    public void granted() {
                        SystemLocationManagerNew.getInstance().registerGpsChangedListener(mGpsChangedListener);
                    }

                    @Override
                    public void deny() {
                        Toast.makeText(TeamCreateLocationActivity.this,
                                "因未获得定位权限，所以不能自动定位到当前位置，请手动选择集合地点", Toast.LENGTH_LONG).show();
                    }
                });
    }
}